package com.hsd.znsh.utils;

import com.hsd.znsh.entity.Monitor;
import com.hsd.znsh.enums.ResultEnum;
import com.hsd.znsh.vlc.VlcThread;

import javax.servlet.ServletContext;
import javax.sound.sampled.Port;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-04-14 13:49:43
 */
public class VlcUtil {

    public static String getVideoStreamAddress(ServletContext servletContext, Monitor monitor){
        VlcThread vlc=getVlc(servletContext,monitor);
        if(vlc==null) startVlc(servletContext,monitor);
        return ":"+(8080+monitor.getId())+"/video";
    }

    public static VlcThread getVlc(ServletContext servletContext, Integer monitorId){
        Map<Integer,VlcThread> map=getMap(servletContext);
        VlcThread vlc=map.get(monitorId);
        return vlc;
    }

    public static VlcThread getVlc(ServletContext servletContext, Monitor monitor){
        return getVlc(servletContext,monitor.getId());
    }

    public static void startVlc(ServletContext servletContext, Monitor monitor){
        Map<Integer,VlcThread> map=getMap(servletContext);
        String sout=":"+(8080+monitor.getId())+"/video";
        System.out.println(monitor.getVideoStreamAddress());
        VlcThread vlc=new VlcThread(monitor.getVideoStreamAddress(),sout);
        vlc.start();
        while(!PortUtil.findPortInLisnter(8080+monitor.getId())){

        }
        map.put(monitor.getId(),vlc);
        servletContext.setAttribute("vlcList",map);
    }

    public static void endVlc(ServletContext servletContext,  Monitor monitor){
        endVlc(servletContext,monitor.getId());
    }

    public static void endVlc(ServletContext servletContext,  Integer monitorId){
        Map<Integer,VlcThread> map=getMap(servletContext);
        VlcThread vlc=map.get(monitorId);
        if(vlc!=null){
            vlc.getProcess().destroy();
            map.remove(monitorId);
        }
        servletContext.setAttribute("vlcList",map);
    }

    public static Map<Integer,VlcThread>  getMap(ServletContext servletContext){
        Map<Integer,VlcThread> map=(Map<Integer,VlcThread>)servletContext.getAttribute("vlcList");
        if(map==null) map=new HashMap<>();
        return map;
    }

}
